import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:wanAndroid/bean/coin_personal_bean.dart';
import 'package:wanAndroid/bean/coin_rank_list_bean.dart';
import 'package:wanAndroid/common/http/http_service.dart';
import 'package:wanAndroid/common/http/http_uts.dart';
import 'package:wanAndroid/common/uts/log_uts.dart';
import 'package:wanAndroid/common/uts/toast_uts.dart';
import 'package:wanAndroid/common/uts/ui_uts.dart';
import 'package:wanAndroid/res/colors.dart';

class PagePersonalPoints extends StatefulWidget {
  //启动
  static Future<bool> start(BuildContext context,
      {Map<String, dynamic> args}) async {
    return await Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => PagePersonalPoints(),
        ));
  }

  @override
  State<StatefulWidget> createState() => _PagePersonalPoints();
}

class _PagePersonalPoints extends State<PagePersonalPoints> {
  List<Datas> datas = [];
  RefreshController _refreshController;
  int _currPage = 1;
  int _pageCount = 0;

  ///
  bool isUp = true;

  //个人数据
  Coin_personal_bean coinPersonalBean;

  @override
  void initState() {
    _refreshController = RefreshController(initialRefresh: true);
    getCoinPersnal();
    super.initState();
  }

  @override
  Widget build(BuildContext context) => Scaffold(
        backgroundColor: ResColors.scaffoldColor,
        appBar: AppBar(
          title: UiUts.getTitle("个人积分"),
          centerTitle: false,
        ),
        body: SmartRefresher(
          enablePullDown: true,
          enablePullUp: isUp,
          onRefresh: () {
            setState(() {
              _currPage = 1;
            });
            getData();
          },
          onLoading: () {
            setState(() {
              _currPage += 1;
            });
            getData();
          },
          header: ClassicHeader(),
          footer: ClassicFooter(),
          controller: _refreshController,
          child: null == datas || datas.length == 0
              ? UiUts.getEmpty(clickListener: () {})
              : ListView.separated(
                  itemBuilder: (context, index) {
                    if (index == 0) {
                      return getHeader();
                    } else {
                      Datas d = datas[index - 1];
                      return getViewItem(d);
                    }
                  },
                  separatorBuilder: (context, index) {
                    return UiUts.getDivider(
                        height: 5, color: ResColors.scaffoldColor);
                  },
                  itemCount: 0 == datas.length ? 1 : datas.length + 1,
                ),
        ),
      );

  /// 获取数据
  Future<void> getData() async {
    HttpService.coin(_currPage,
        callback: HttpCallback((rsp) {
          UiUts.finishRefresh(_refreshController);
          CoinRankListBean result = CoinRankListBean.fromJson(rsp.data);
          if (HttpUts.isSuccess(result.errorCode)) {
            setState(() {
              _pageCount = result.data.pageCount;
              if (_currPage == 11) {
                datas = result.data.datas;
              } else {
                datas.addAll(result.data.datas);
              }
              isUp = !(_pageCount == _currPage);
            });
          } else {
            ToastUts.showToast(context, text: result.errorMsg);
          }
        }, (e) {
          UiUts.finishRefresh(_refreshController);
        }));
  }

  ///获取个人积分
  Future<void> getCoinPersnal() async {
    HttpService.userInfo(HttpCallback((rsp) {
      setState(() {
        coinPersonalBean = Coin_personal_bean.fromJson(rsp.data);
      });
      if (HttpUts.isSuccess(coinPersonalBean.errorCode)) {
        ///请求成功
      } else {
        ToastUts.showToast(context, text: coinPersonalBean.errorMsg);
      }
    }, (e) {
      LogUts.netLog(e, tag: "个人积分");
    }));
  }

  Widget getViewItem(Datas data) {
    return Container(
      margin: null,
      alignment: Alignment.center,
      padding: const EdgeInsets.symmetric(
        horizontal: 15,
      ),
      constraints: BoxConstraints(
        minHeight: 50,
      ),
      width: double.infinity,
      decoration: BoxDecoration(
        border: Border.all(color: Colors.white, width: 1),
        color: Colors.white,
        borderRadius: BorderRadius.circular(5),
      ),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          UiUts.getText(
            "${data.username}",
            fontSize: 17,
            color: Color(0xff545454),
          ),
          UiUts.getText(
            "${data.coinCount}",
            color: Colors.orangeAccent,
            fontSize: 15,
          )
        ],
      ),
    );
  }

  Widget getHeader() {
    return Container(
      padding: const EdgeInsets.only(
        top: 15,
        bottom: 10,
      ),
      width: double.infinity,
      decoration: BoxDecoration(
        color: Colors.white,
      ),
      height: 200,
      alignment: Alignment.center,
      child: Text.rich(
        TextSpan(
          children: [
            TextSpan(
                children: [
                  TextSpan(
                      text:
                          "${coinPersonalBean.data.rank}--等级：${coinPersonalBean.data.level}",
                      style: TextStyle(
                        fontSize: 15,
                        color: Colors.red,
                      ))
                ],
                text: "排名：",
                style: TextStyle(
                  fontSize: 12,
                  color: Colors.black,
                ))
          ],
          text: "${coinPersonalBean.data.coinCount} \n",
          style: TextStyle(
            fontSize: 50,
            color: Colors.amber,
          ),
        ),
      ),
    );
  }
}
